package cn.bs.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.concurrent.TimeUnit;

@Configuration
public class LoginInterceptor implements WebMvcConfigurer {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new HandlerInterceptor(){
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                // 放行 OPTIONS 请求
                if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
                    return true;
                }

                String token = request.getHeader("Authorization");
                System.out.println("token:" + token);
                if (token != null && redisTemplate.opsForValue().get(token) != null) {
                    redisTemplate.expire(token, 30, TimeUnit.MINUTES); // 刷新 token 过期时间
                    return true;
                }

                System.out.println("用户未登录。。。");
                response.setStatus(401);
                return false;
            }
        }).excludePathPatterns("/user/login", "/user/register", "/user/logout",
                "/", "/dishes/getDishes",
                "/canteen/getCanteen", "/canteen/getSeatList",
                "/canteen/getDishesByCanteenId","/community/getReview",
                "/community/getPost","/community/getComment",
                "/community/getPostById/**",
                "/community/getCommentByFather",
                "/alipay/**",
                "/api/alipay/pay",
                "/api/alipay/toSuccess");

    }
}















